'use strict';

const BaseService = require('./base');

const { API } = require('../../config/config.api.' + process.env.EGG_SERVER_ENV + '.js')
const printerApiUrlList = API.printerApiUrlList;
const { fileToPrint } = require('../utils/print.js');
class HandeService extends BaseService {

  async printAttachment(attachmentList) {
    if (attachmentList && attachmentList.length > 0) {   
      let result = [];
      for (let index = 0; index < attachmentList.length; index++) {
        let element = attachmentList[index];
        if (process.env.EGG_SERVER_ENV == "local") {
          element["url"] = element.fujian.replace('crm.handeaxle.com', '173.82.243.117');
        }else{
          element["url"] = element.fujian;
        }
        try {
          if (element.url.indexOf(".doc") !== -1 || element.url.indexOf(".xls") !== -1 || element.url.indexOf(".pdf") !== -1) {
            const res = await fileToPrint(element.new_name, element.new_type, element.url);
            result.push(res)
          } else {
            result.push({ errmsg: "Just support docx doc xls xlsx pdf ,not supported others files!" })
          }
        } catch (error) {
          result.push(error)
        }
      }
      return result;

    } else {
      throw new Exception("data is null or data length is 0!");
    }
  }
  async getUserSetting() {
    const self = this;
    const result = await self.ipcCall('hande.getUserSetting');
    return result;
  }
  async setUserSetting(userSetting) {
    const self = this;
    const result = await self.ipcCall('hande.setUserSetting', userSetting);
    return result;
  }


  async getPrinterList() {
    const res = {
      code: 1000,
      message: 'unknown error',
    };
    try {
      //throw new Error('Sync Error');
      const headersObj = {
        'Content-Type': 'application/json',
      };
      this.app.logger.info('[HandeService] [GetOrderDetails]: headers:%', headersObj);

      process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';
      const responseDevices = await this.app.curl(printerApiUrlList.devices, {
        method: 'GET',
        headers: headersObj,
        dataType: 'json',
        timeout: 3000,
        strictSSL: false
      });
      const result = responseDevices.data;
      console.log(result);
      if (this.app.config.env === 'local') {
        this.app.logger.info('[HandeService] [GetOrderList]: info result:%j', result);
      }
      if (result.code !== 'success') {
        this.app.logger.error('[HandeService] [GetOrderList]: res error result:%j', result);
      }
      return result;
    } catch (e) {
      this.app.logger.error('[HandeService] [GetOrderList]:  ERROR ', e);
    }
    return res;
  }

  async getPrinterInfo(command, portName) {
    const res = {
      code: 1000,
      message: 'unknown error',
    };
    try {
      //throw new Error('Sync Error');
      const headersObj = {
        'Content-Type': 'application/json',
      };
      this.app.logger.info('[HandeService] [GetOrderDetails]: headers:%', headersObj);
      const url = printerApiUrlList[command] + portName;
      process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';
      const statusDevices = await this.app.curl(url, {
        method: 'GET',
        headers: headersObj,
        dataType: 'json',
        timeout: 3000,
      });
      const result = statusDevices.data;
      console.log(result);
      if (this.app.config.env === 'local') {
        this.app.logger.info('[HandeService] [GetOrderList]: info result:%j', result);
      }
      if (result.code !== 'success') {
        this.app.logger.error('[HandeService] [GetOrderList]: res error result:%j', result);
      }
      return result;
    } catch (e) {
      this.app.logger.error('[HandeService] [GetOrderList]:  ERROR ', e);
    }
    return res;
  }





  async checkPrinter(portName) {
    const res = {
      code: 1000,
      message: 'unknown error',
    };
    try {
      //throw new Error('Sync Error');
      const headersObj = {
        'Content-Type': 'application/json',
      };
      this.app.logger.info('[HandeService] [GetOrderDetails]: headers:%', headersObj);

      process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';
      const url = printerApiUrlList.status + portName;
      const statusDevices = await this.app.curl(url, {
        method: 'GET',
        headers: headersObj,
        dataType: 'json',
        timeout: 3000,
      });
      const result = statusDevices.data;
      console.log(result);
      if (this.app.config.env === 'local') {
        this.app.logger.info('[HandeService] [GetOrderList]: info result:%j', result);
      }
      if (result.code !== 'success') {
        this.app.logger.error('[HandeService] [GetOrderList]: res error result:%j', result);
      }
      return result;
    } catch (e) {
      this.app.logger.error('[HandeService] [GetOrderList]:  ERROR ', e);
    }
    return res;
  }


  async getOrderList(postData, authorization) {
    const res = {
      code: 1000,
      message: 'unknown error',
    };
    try {
      //throw new Error('Sync Error');
      const headersObj = {
        'Content-Type': 'application/json',
        'Authorization': authorization
      };
      this.app.logger.info('[HandeService] [GetOrderDetails]: headers:%', headersObj);
      this.app.logger.info('[HandeService] [GetOrderDetails]: postData:%', postData);
      this.app.logger.info('[HandeService] [GetOrderDetails]: URL:%', API.BRIDGE_SHIP_QUERY_API);
      this.app.logger.info('[HandeService] [GetOrderDetails]: NODE_ENV:%', process.env.NODE_ENV);
      this.app.logger.info('[HandeService] [GetOrderDetails]: EGG_SEV:%', process.env.EGG_SERVER_ENV);

      const response = await this.app.curl(API.BRIDGE_SHIP_QUERY_API, {
        method: 'POST',
        headers: headersObj,
        data: postData,
        dataType: 'json',
        timeout: 30000,
      });
      const result = response.data;
      console.log(result);
      if (this.app.config.env === 'local') {
        this.app.logger.info('[HandeService] [GetOrderList]: info result:%j', result);
      }
      if (result.code !== 'success') {
        this.app.logger.error('[HandeService] [GetOrderList]: res error result:%j', result);
      }
      return result;
    } catch (e) {
      this.app.logger.error('[HandeService] [GetOrderList]:  ERROR ', e);
    }
    return res;
  }

  async getOrderDetails(postData, authorization) {
    const res = {
      code: 1000,
      message: 'unknown error',
    };
    try {
      //throw new Error('Sync Error');
      const headersObj = {
        'Content-Type': 'application/json',
        'Authorization': authorization
      };
      this.app.logger.info('[HandeService] [GetOrderDetails]: headers:%', headersObj);
      this.app.logger.info('[HandeService] [GetOrderDetails]: postData:%', postData);
      this.app.logger.info('[HandeService] [GetOrderDetails]: url:%', API.BRIDGE_SHIP_DET_QUERY_API);

      const response = await this.app.curl(API.BRIDGE_SHIP_DET_QUERY_API, {
        method: 'POST',
        headers: headersObj,
        data: postData,
        dataType: 'json',
        timeout: 30000,
      });
      this.app.logger.info('[HandeService] [GetOrderDetails]: info response:%j', response);
      const result = response.data;
      if (this.app.config.env === 'local') {
        this.app.logger.info('[HandeService] [GetOrderDetails]: info result:%j', result);
      }
      if (result.code !== 'success') {
        this.app.logger.error('[HandeService] [GetOrderDetails]: res error result:%j', result);
      }
      return result;
    } catch (e) {
      this.app.logger.error('[HandeService] [GetOrderDetails]:  ERROR ', e);
    }
    return res;
  }

}

module.exports = HandeService;